function [embeddedImg,capacity]=BBE(im,s)
[M,N]=size(im);   r1=mod(size(im,1),s);   c1=mod(size(im,2),s);
embeddedImg=im;
na=calNa(s);   p=max(ceil(log2(na)),1);
[capacity,BCapacity,bbBits,bIndex]=GetImgCapacity(im(1:end-r1,1:end-c1), s);
if capacity>0
    mess=[bbBits;randi(2, capacity,1)-1];
    index=1;
    for i=1:s:M-r1
        for j=1:s:N-c1
        bij=im(i:i+s-1,j:j+s-1);
        if bIndex(index)==0
            bij(1,1)=0; bij(1,2)=0;
        else
            cb=BCapacity(i,j).cb;
            qi=BCapacity(i,j).qi;
            n0=BCapacity(i,j).n0;
            n1=BCapacity(i,j).n1;
            m=BCapacity(i,j).m;
            pos=BCapacity(i,j).pos;
            
            bij=bij';  bij=bij(:);
            if n0==0  % case1
                bij(1:2)=1; bij(3:end)=mess(1:cb);  mess(1:cb)=[];  
            elseif n1==0  % case2
                bij(1)=1; bij(2)=0; bij(3:end)=mess(1:cb);  mess(1:cb)=[]; 
            elseif n0<n1  % case3
                bij(1)=0; bij(2:3)=1; 
                pv=CalPvalue(m,p);  bij(4:4+p-1)=pv;  
                posInfo=CalPosInfo(pos,qi);  bij(4+p:4+p+length(posInfo)-1)=posInfo;  
                L=s^2-(4+p+length(posInfo)-1);
                bij(4+p+length(posInfo):end)=mess(1:L); mess(1:L)=[];
            else  % case4
                bij(1)=0; bij(2)=1; bij(3)=0; 
                pv=CalPvalue(m,p);  bij(4:4+p-1)=pv;  
                posInfo=CalPosInfo(pos,qi);  bij(4+p:4+p+length(posInfo)-1)=posInfo;  
                L=s^2-(4+p+length(posInfo)-1);
                bij(4+p+length(posInfo):end)=mess(1:L); mess(1:L)=[];
            end
            bij=reshape(bij,[s,s]); bij=bij';
        end
        index=index+1;
        embeddedImg(i:i+s-1,j:j+s-1)=bij;
        end
    end
end
end


function pv=CalPvalue(p,L)
pv=str2num(dec2bin(p,L)');#数组
if length(pv)>L
    pv=pv(2:end);
end
end

function posInfo=CalPosInfo(pos,qi)
posInfo=[];
for i=1:length(pos)
    if i==1  % convert pos(i) to qi(i)-bit binary sequence
        posInfo=[posInfo; CalPvalue(pos(i),qi(i))];
    else
        posInfo=[posInfo; CalPvalue(pos(i)-pos(i-1),qi(i))];
    end
end
end